from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from typing import Optional

from app.services.simple_json_auth_service import SimpleJSONAuthService
from app.services.simple_json_task_service import SimpleJSONTaskService

# 安全方案
security = HTTPBearer(auto_error=False)

# 服务实例
auth_service = SimpleJSONAuthService()
task_service = SimpleJSONTaskService()

def get_auth_service() -> SimpleJSONAuthService:
    """获取认证服务"""
    return auth_service

def get_task_service() -> SimpleJSONTaskService:
    """获取任务服务"""
    return task_service

def get_current_user(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
) -> dict:
    """获取当前用户 - 简化版本"""
    if not credentials:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="未提供认证令牌",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    user = auth_service.get_current_user(credentials.credentials)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证令牌",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    return user

def get_current_user_optional(
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)
) -> Optional[dict]:
    """获取当前用户（可选）"""
    if not credentials:
        return None
    
    return auth_service.get_current_user(credentials.credentials)
